// File: jmcomic-core/src/main/java/dev/jukomu/common/base/packer/JsonPacker.java
package dev.jukomu.common.base.packer;

import dev.jukomu.common.util.json.JsonUtils;

import java.io.File;
import java.io.IOException;

/**
 * 使用Jackson库进行JSON序列化和反序列化的Packer实现。
 */
public class JsonPacker extends AbstractPacker {

    public JsonPacker() {
        this.packMode = "w"; // text write
        this.unpackMode = "r"; // text read
    }

    @Override
    protected void dump(File file, Object obj) throws IOException {
        JsonUtils.writeObjectToFile(file, toSerializableForm(obj));
    }

    @Override
    protected <T> T load(File file, Class<T> clazz) throws IOException, ClassNotFoundException {
        // If clazz is null, load as a generic Map
        if (clazz == null) {
            return (T) JsonUtils.loadFileAsMap(file);
        }
        // If clazz is provided, try to load as that type
        return JsonUtils.parseString(JsonUtils.loadFileAsMap(file).toString(), clazz); // Jackson can map Map to POJO
    }

    @Override
    public <T> T unpackByString(String text, Class<T> clazz) throws IOException {
        if (clazz == null) {
            return (T) JsonUtils.parseStringAsMap(text);
        }
        return JsonUtils.parseString(text, clazz);
    }
}